package com.hengxinguotong.zhihuichengjian.ui.environment.data;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.ImageView;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.EnvironmentDataListAdapter;
import com.hengxinguotong.zhihuichengjian.bean.Environment;
import com.hengxinguotong.zhihuichengjian.bean.EnvironmentListRes;
import com.hengxinguotong.zhihuichengjian.ui.BaseActivity;
import com.hengxinguotong.zhihuichengjian.ui.environment.data.EnvironmentDataDetailActivity;
import com.hengxinguotong.zhihuichengjian.utils.Constants;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.view.PullableRecyclerView;
import com.jingchen.pulltorefresh.PullToRefreshLayout;
import com.lidroid.xutils.http.RequestParams;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @CopyRight 恒信国通信息科技
 * @Author WuLei
 * @Date 2019/2/23
 *
 * 环境检测数据
 */

public class EnvironmentDataListActivity extends BaseActivity implements View.OnClickListener, EnvironmentDataListAdapter.OnClickListener {
    @BindView(R.id.refresh_list)
    PullToRefreshLayout refreshList;
    @BindView(R.id.empty_img)
    ImageView emptyImg;

    private PullableRecyclerView dataRv;

    private int pageIndex = 1;
    private List<Environment> environmentList;
    private EnvironmentDataListAdapter environmentListAdapter;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case Constants.UPDATE:
                    List<Environment> datas = (List<Environment>) msg.obj;
                    bindData(datas);
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_environment_data_list);
        ButterKnife.bind(this);
        initView();
        initData();
    }

    private void initView() {
        refreshList.setPullUpEnable(false);
        refreshList.setOnPullListener(pullListener);
        dataRv = (PullableRecyclerView) refreshList.getPullableView();
        environmentList = new ArrayList<>();
        environmentListAdapter = new EnvironmentDataListAdapter(this, environmentList);
        environmentListAdapter.setOnClickListener(this);
        dataRv.setAdapter(environmentListAdapter);
        dataRv.setItemAnimator(new DefaultItemAnimator());
//        dataRv.addItemDecoration(new SpacesItemDecoration(20));
        dataRv.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
    }

    private PullToRefreshLayout.OnPullListener pullListener = new PullToRefreshLayout.OnPullListener()
    {
        @Override
        public void onRefresh(PullToRefreshLayout pullToRefreshLayout)
        {
            pageIndex = 1;
            initData();
        }

        @Override
        public void onLoadMore(PullToRefreshLayout pullToRefreshLayout)
        {
            pageIndex = environmentList.size() / Utils.ONCECOUNT + 1;
            initData();
        }
    };

    private void initData(){
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                getEnvironmentList("搜索中…");
            }
        }, 500);
    }

    public void getEnvironmentList(String alert) {

        RequestParams params = new RequestParams();
        params.addBodyParameter("constructionId", SPUtil.getString(this, "constructionid"));
        params.addBodyParameter("type", "5");//3 塔吊 4升降机 5环境监测设备
        params.addBodyParameter("pageNum", pageIndex + "");
        Utils.requestData(alert, this, "/equipmentRegister/queryEquipmentListNew/" + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    EnvironmentListRes res = gson.fromJson(json, EnvironmentListRes.class);
                    if(res.getStatus() == 1){
                        Message msg = handler.obtainMessage();
                        msg.what = Constants.UPDATE;
                        msg.obj = res.getValue();
                        msg.sendToTarget();
                    }else{
                        showToast(res.getMsg());
                        if (pageIndex == 1)
                        {
                            refreshList.refreshFinish(PullToRefreshLayout.FAIL);
                        } else
                        {
                            refreshList.loadmoreFinish(PullToRefreshLayout.FAIL);
                        }
                    }
                }else{
                    showToast("系统异常");
                    if (pageIndex == 1)
                    {
                        refreshList.refreshFinish(PullToRefreshLayout.FAIL);
                    } else
                    {
                        refreshList.loadmoreFinish(PullToRefreshLayout.FAIL);
                    }
                }
            }

            @Override
            public void onFailure(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    showToast(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    showToast("系统异常");
                }
                if (pageIndex == 1)
                {
                    refreshList.refreshFinish(PullToRefreshLayout.FAIL);
                } else
                {
                    refreshList.loadmoreFinish(PullToRefreshLayout.FAIL);
                }
            }
        });
    }

    private void bindData(List<Environment> datas) {
        if (pageIndex == 1)
        {
            refreshList.refreshFinish(PullToRefreshLayout.SUCCEED);
            environmentList = datas;
        } else
        {
            refreshList.loadmoreFinish(PullToRefreshLayout.SUCCEED);
            environmentList.addAll(datas);
        }
        showEmptyView(environmentList.size() == 0);
        if (datas.size() >= Utils.ONCECOUNT)
        {
            refreshList.setPullUpEnable(true);
        } else
        {
            refreshList.setPullUpEnable(false);
        }
        environmentListAdapter.setDataList(environmentList);
    }

    private void showEmptyView(boolean isEmpty){
        if(isEmpty){
            emptyImg.setVisibility(View.VISIBLE);
        }else {
            emptyImg.setVisibility(View.GONE);
        }
    }

    @OnClick({R.id.back_tv})
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.back_tv:
                finish();
                break;
        }
    }

    @Override
    public void onClick(Object o) {
        Environment environment = (Environment) o;
        if(environment == null){
            return;
        }
        Intent intent = new Intent(this, EnvironmentDataDetailActivity.class);
        intent.putExtra("environment", environment);
        startActivity(intent);
    }

}
